<?php
/**
 * 用户相关
 * User: Administrator
 * Date: 2015/10/21
 * Time: 0:58
 */

namespace Api\Controller;


class MemberController extends BeforController
{
    /*
     * 上传头像
     */
    public function avatar()
    {
        $upload           = new \Think\Upload();// 实例化上传类
        $upload->maxSize  = 3145728;// 设置附件上传大小
        $upload->exts     = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
        $upload->hash     = true;
        $upload->rootPath = WEB_ROOT;
        $upload->savePath = 'Uploads' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
        $upload->replace  = false;
        $upload->autoSub  = true;
        $info             = $upload->upload();
        if (empty($info)) {
            $this->response(['code' => __LINE__, 'msg' => $upload->getError()], 'json');
        }
        $info = array_pop($info);
        $file = $info['savepath'] . $info['savename'];
        // 保存头像到数据库中
        $dbMemer = M('Member');
        $rep     = $dbMemer->where(['muid' => $this->_userinfo['muid']])->field('avatar')->save(['avatar' => $file]);
        if ($rep) {
            $this->response(['code' => 0, 'data' => ['headimgUrl' => U($file, '', '', true)]], 'json');
        } else {
            $this->response(['code' => __LINE__, '头像上传失败'], 'json');
        }
    }

    /**
     * 会员信息
     */
    public function info()
    {
        // 会员id
        $muid = $this->_userinfo['muid'];
        // putonghi
        $dbmember = M('MemberCount');
        $data     = $dbmember->field([
            'follow as attentionCount',
            'company as company',
            'office as office',
            'subscribe as subscriptionCount',
            'idcard as idCard'
        ])->where([
            'mid' => $muid
        ])->join('__MEMBER__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
            'LEFT')->find();
        if (empty($data)) {
            $return = [
                'attentionCount'    => 0,
                'subscriptionCount' => 0,
                'company'           => '',
                'office'            => '',
                'idCard'            => ''
            ];
        } else {
            $return = [
                'attentionCount'    => intval($data['attentionCount']),
                'subscriptionCount' => intval($data['subscriptionCount']),
                'company'           => (empty($data['company']) ? '' : $data['company']),
                'office'            => (empty($data['office']) ? '' : $data['office']),
                'idCard'            => (empty($data['idCard']) ? '' : $data['idCard'])
            ];
        }
        $return['headimgUrl']      = empty($this->_userinfo['avatar']) ? '' : U($this->_userinfo['avatar'], '', '',
            true);
        $return['introduction']    = $this->_userinfo['about'];
        $return['phone']           = $this->_userinfo['nickname'];
        $return['sex']             = $this->_userinfo['sex'];
        $return['shareRegisterID'] = U('Home/Login/reg', ['ref' => base64_encode($this->_userinfo['muid'])], 'html',
            true);
        $return['username']        = $this->_userinfo['nickname'];
        $this->response(['code' => 0, 'data' => $return], 'json');
    }

    /**
     * 修改信息
     */
    public function change()
    {
        $about    = I('post.introduction', '', 'trim');
        $company  = I('post.company', '', 'trim');
        $office   = I('post.office', '', 'trim');
        $nickname = I('post.username', '', 'trim');
        $sex      = I('post.sex', 0, 'intval');

        $dbmemer = M('Member');
        $dbmemer->field(['sex', 'about', 'nickname','office'])->data([
            'sex'      => $sex,
            'about'    => $about,
            'nickname' => $nickname,
            'office'    => $office,
            'company'   => $company,
        ])->where(['muid' => $this->_userinfo['muid']])->save();

        $this->response(['code' => 0, 'msg' => 'ok'], 'json');

    }

    /**
     * 问答列表
     */
    public function alists()
    {
        $showCount = I('post.showCount', 15, 'intval');
        $pageCount = I('post.pageCount', 1, 'intval');
        $pageCount = max($pageCount, 1);
        $type      = I('post.type', 1, 'intval');
        $user_type = $this->_userinfo['type'];
        $where     = [];
        if($type==1){
            $where['atime'] = ['neq', 0];
            $where['_complex']=['_logic'=>'or','aid'=>$this->_userinfo['muid'],'quid'=>$this->_userinfo['muid']];
        }elseif($type==2){
            $where['quid'] = $this->_userinfo['muid'];
            $where['atime'] = 0;
        }elseif($type==3){
            $where['atime'] = ['neq', 0];
        }elseif($type==4){
            $where['aid']   = ['in', [0, $this->_userinfo['muid']]];
            $where['atime'] = 0;
        }
        $db    = M('Qa');
        $count = $db->where($where)->count();
        if (empty($count)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无数据'], 'json');
        }
        $data = $db->where($where)->limit((($pageCount - 1) * $showCount) . ',' . $showCount)->select();
        if (empty($data)) {
            $this->response(['code' => __LINE__, 'msg' => '暂无数据'], 'json');
        }
        $muid = [];
        foreach ($data as $k => $v) {
            $muid[$v['quid']] = $v['quid'];
            $muid[$v['aid']]  = $v['aid'];
        }
        $dbmemer = M('Member');
        $dbmemer = $dbmemer->field(['muid', 'nickname', 'avatar'])->where(['muid' => ['IN', $muid]])->select();
        $member  = [];
        foreach ($dbmemer as $k => $v) {
            $member[$v['muid']] = $v;
        }
        foreach ($data as $k => $v) {
            $m = [
                'askMsg'      => $v['qcontent'],
                'askTime'     => date('Y-m-d H:i:s',$v['qtime']),
                'askUser'     => $member[$v['quid']]['nickname'],
                'askUserHead' => U($member[$v['quid']]['avatar'], '', '', true),
                'msgId'       => $v['id']
            ];
            if ($type != 2) {
                $m['ansMsg']      = $v['acontent'];
                $m['ansTime']     = date('Y-m-d H:i:s',$v['atime']);
                $m['ansUser']     = $member[$v['aid']]['nickname'];
                $m['ansUserHead'] = U($member[$v['aid']]['avatar'], '', '', true);
            }
            $list[$k] = $m;
        }
        $this->response(['code' => 0, 'data' => ['list' => $list, 'totalPage' => $count]], 'json');
    }

    /**
     * 问题回答
     */
    public function areply()
    {
        $msgId       = I('post.msgId', 0, 'intval');
        $msgConstent = I('post.msgConstent', '', 'trim');
        if (empty($msgId) || empty($msgConstent)) {
            $this->response(['code' => __LINE__, 'msg' => '参数不正确'], 'json');
        }
        $db    = M('Qa');
        $count = $db->where(['id' => $msgId, 'atime' => 0])->where([
            'aid' => [
                'in',
                [0, $this->_userinfo['muid']]
            ]
        ])->find();
        if (empty($count)) {
            $this->response(['code' => __LINE__, 'msg' => '问题已经回答'], 'json');
        }

        if($count['quid']==$this->_userinfo['muid']){
            $this->response(['code' => __LINE__, 'msg' => '不可自问自答'], 'json');
        }
        $ref = $db->field(['aid', 'acontent', 'atime', 'aip'])->data([
            'aid'      => $this->_userinfo['muid'],
            'acontent' => $msgConstent,
            'atime'    => time(),
            'aip'      => get_client_ip()
        ])->where(['id' => $msgId])->save();
        if ($ref) {
            $this->response(['code' => 0, 'msg' => 'ok'], 'json');
        } else {
            $this->response(['code' => __LINE__, 'msg' => '解答失败'], 'json');
        }
    }

    /**
     * 金币任务
     */
    public function tasks()
    {
        $db          = M('Tasks');
        $total       = $db->where(['status' => 1])->count();
        $data        = $db->field([
            'groups',
            'integration',
            'title',
            'desp',
            'icon',
            'adsimg',
            'ishot',
            'atime'
        ])->where(['status' => 1])->order(['atime' => 'desc'])->select();
        $scoreMsg    = $data[0]['desp'];
        $scoreImgURL = U($data[0]['adsimg'], '', '', true);
        unset($data[0]);
        $lists = [];
        $types = ['新手任务', '日常任务', '成长任务'];
        foreach ($data as $k => $val) {
            unset($data[$k]);
            $data[$val['groups']]['groupName']   = $types[$val['groups']];
            $data[$val['groups']]['grouplist'][] = [
                'isAccepted'    => 1,
                'isFinished'    => 0,
                'itemIcon'      => U($val['icon'], '', '', true),
                'itemMsg'       => $val['desp'],
                'itemScore'     => $val['integration'],
                'itemTitle'     => $val['title'],
                'itemTimeEnd'   => '',
                'itemTimeStart' => date('Y-m-d', $val['atime'])
            ];
        }
        foreach ($data as $val) {
            $lists[] = $val;
        }
        $data = [
            'list'        => $lists,
            'myScore'     => $this->_userinfo['credit'],
            'scoreMsg'    => $scoreMsg,
            'scoreJump'   => '',
            'scoreImgURL' => $scoreImgURL,
            'totalPage'   => $total
        ];
        $this->response(['code' => 0, 'data' => $data], 'json');
    }

    /**
     * 牛人搜索
     */
    public function search()
    {
        $type      = I('post.type', 0, 'intval');
        $keyword   = I('post.keyword', '', 'trim');
        $dbmember  = M('Member');
        $pageCount = max(1, I('post.pageCount', 1, 'intval'));
        $showCount = max(1, I('post.showCount', 15, 'intval'));
        if (empty($type)) {
            if (empty($keyword)) {
                $this->response(['code' => __LINE__, 'msg' => '请输入牛人信息']);
            }
            $total  = $dbmember->where(['type' => 1, 'nickname' => ['like', $keyword . '%']])->count();
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->where(['type' => 1, 'nickname' => ['like', $keyword . '%']])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        $total = $dbmember->where(['type' => 1])->count();
        // 大盘预测准确率
        if ($type == 1) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['proper' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        if ($type == 2) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['income' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 人气牛人
        if ($type == 3) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['follow' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 长胜牛人
        if ($type == 4) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['winrate' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 活力牛人
        if ($type == 5) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['sn' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 日收益榜
        if ($type == 6) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['dyield' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 周收益榜
        if ($type == 7) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['wyield' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        // 月收益榜
        if ($type == 8) {
            $ulists = $dbmember->field([
                'muid as userId',
                'avatar as imageUrl',
                'nickname as name'
            ])->join('__MEMBER_COUNT__ ON __MEMBER_COUNT__.mid=__MEMBER__.muid',
                'LEFT')->where(['type' => 1])->order(['myield' => 'desc'])->limit(($pageCount - 1) * $showCount,
                $showCount)->select();
        }
        if(empty($ulists)){
            $this->response(['code'=>__LINE__,'msg'=>'暂无数据'],'json');
        }
        // 提取uid
        foreach($ulists as $k=>$v){
            $uids[$v['userId']]=$v['userId'];
        }
        // 去除最后一次的持仓记录
        $dbposition=M('StockPosition')->field('muid,count(sid) as stocks,sum(total) as rateOfStock')->where(['muid'=>['in',$uids]])->order(['atime'=>'desc'])->group('muid')->select();
        $plist=[];
        foreach($dbposition as $value){
            $plist[$value['muid']]=$value;
        }
        // 读取统计数据
        $dbcount = M('MemberCount')->field(['dyield as totalRate','winrate as rateOfWin','avadays as avaDays','myield as avaIncome','avatrade as avaTradeTimes','mid'])->where(['mid'=>['in',$uids]])->select();
        foreach($dbcount as $k=>$value){
            $dbcount[$value['mid']]=$value;
            unset($dbcount[$k]);
        }
        // 搜索关注列表
        $follow = M('Follow')->field('nbuid')->where(['nbuid'=>['in',$uids],'muid'=>$this->_userinfo['muid']])->select();
        foreach($follow as $k=>$v){
            unset($follow[$k]);
            $follow[$v['nbuid']]=$v['nbuid'];
        }
        // 搜索订阅列表
        $subs = M('Subs')->field('nbuid')->where(['nbuid'=>['in',$uids],'muid'=>$this->_userinfo['muid']])->select();
        foreach($subs as $k=>$v){
            unset($subs[$k]);
            $subs[$v['nbuid']]=$v['nbuid'];
        }
        foreach($ulists as $k=>$v){
            $v['imageUrl']=U($v['imageUrl'],'','',true);
            $v['userId']=floatval($v['userId']);
            $v['isAttention']=isset($follow[$v['userId']])?1:0;
            $v['isSubscription']=isset($subs[$v['userId']])?1:0;
            $v['stocks']=floatval($plist[$v['userId']]['stocks']);
            $v['rateOfStock']=0.3856;
            $v['itemName']='A股模拟交易';
            $v['avaDays']=floatval($dbcount[$value['mid']]['avaDays']);
            $v['totalRate']=floatval($dbcount[$value['mid']]['totalRate']);
            $v['avaIncome']=floatval($dbcount[$value['mid']]['avaIncome']);
            $v['avaTradeTimes']=floatval($dbcount[$value['mid']]['avaTradeTimes']);
            $v['rateOfWin']=floatval($dbcount[$value['mid']]['rateOfWin']);
            $ulists[$k]=$v;
        }
        $this->response(['code'=>0,'data'=>['totalCount'=>floatval($total),'list'=>$ulists]], 'json');
    }

    /**
     * 牛人动态
     */
    public function trends(){
        $dbmember  = M('Member');
        $pageCount = max(1, I('post.pageCount', 1, 'intval'));
        $showCount = max(1, I('post.showCount', 15, 'intval'));
        $total  = $dbmember->where(['type' => 1])->count();
        $ulists = $dbmember->field([
            'muid as GUID',
            'avatar as headimgUrl',
            'nickname as username'
        ])->where(['type' => 1])->limit(($pageCount - 1) * $showCount,
            $showCount)->select();
        if(empty($ulists)){
            $this->response(['code'=>0,'msg'=>'暂无数据'],'json');
        }
        $uids=[];
        foreach($ulists as $v){
            $uids[$v['GUID']]=$v['GUID'];
        }
        // 搜索关注列表
        $follow = M('Follow')->field('nbuid')->where(['nbuid'=>['in',$uids],'muid'=>$this->_userinfo['muid']])->select();
        foreach($follow as $k=>$v){
            unset($follow[$k]);
            $follow[$v['nbuid']]=$v['nbuid'];
        }
        // 搜索订阅列表
        $subs = M('Subs')->field('nbuid')->where(['nbuid'=>['in',$uids],'muid'=>$this->_userinfo['muid']])->select();
        foreach($subs as $k=>$v){
            unset($subs[$k]);
            $subs[$v['nbuid']]=$v['nbuid'];
        }
        // 获取统计比

        //获取操作记录
        $logs = M('StockTradesLog')->field(['total','code','price','muid','addtime'])->where(['muid'=>['in',$uids]])->order(['addtime'=>'desc'])->group('muid')->select();
        $codes=[];
        foreach($logs as $k=>$v){
            unset($logs[$k]);
            $logs[$v['muid']]=$v;
            $codes[$v['code']]=$v['code'];
        }
        $codes = M('Stock')->field('code,name')->where(['code'=>['in',$codes]])->select();
        foreach($codes as $k=>$v){
            unset($codes[$k]);
            $codes[$v['code']]=$v['name'];
        }

        foreach($ulists as $k=>$v){
            $v['headimgUrl']=empty($v['headimgUrl'])?'':U($v['headimgUrl'],'','',true);
            $v['isAttention']=isset($follow[$v['GUID']])?1:0;
            $v['isSubscription']=isset($subs[$v['GUID']])?1:0;
            $v['price']=isset($logs[$v['GUID']]['price'])?$logs[$v['GUID']]['price']:0;
            $v['stockID']=empty($logs[$v['GUID']]['code'])?'':$logs[$v['GUID']]['code'];
            $v['stockname']=empty($codes[$logs[$v['GUID']]['code']])?'':$codes[$logs[$v['GUID']]['code']];
            $v['time']=empty($logs[$v['GUID']]['addtime'])?'':date('Y-m-d',$logs[$v['GUID']]['addtime']);
            $v['monthRate']='10';
            $v['winRate']='10';
            $v['rate']='10';
            $ulists[$k]=$v;
        }
        $this->response(['code'=>0,'msg'=>'ok','data'=>['pageCount'=>$total,'list'=>$ulists]],'json');
    }

}
